package config

import (
	"encoding/json"
	"fmt"
	"os"
)

// Config 主配置结构
type Config struct {
	Server     ServerConfig     `json:"server"`
	GUIService GUIServiceConfig `json:"guiService"`
	Defaults   DefaultsConfig   `json:"defaults"`
	GUI        GUIConfig        `json:"gui"`
}

// ServerConfig MCP服务器配置
type ServerConfig struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

// GUIServiceConfig GUI服务配置
type GUIServiceConfig struct {
	URL                 string `json:"url"`
	HealthCheckInterval int    `json:"healthCheckInterval"`
	AutoStart           bool   `json:"autoStart"`
}

// DefaultsConfig 默认值配置
type DefaultsConfig struct {
	Timeout  int    `json:"timeout"`
	LogLevel string `json:"logLevel"`
}

// GUIConfig GUI界面配置
type GUIConfig struct {
	Port         int    `json:"port"`
	Theme        string `json:"theme"`
	WindowWidth  int    `json:"windowWidth"`
	WindowHeight int    `json:"windowHeight"`
	AlwaysOnTop  bool   `json:"alwaysOnTop"`
}

// LoadConfig 从文件加载配置
func LoadConfig(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}

	var cfg Config
	if err := json.Unmarshal(data, &cfg); err != nil {
		return nil, fmt.Errorf("failed to parse config: %w", err)
	}

	if err := cfg.Validate(); err != nil {
		return nil, fmt.Errorf("invalid config: %w", err)
	}

	return &cfg, nil
}

// Validate 验证配置有效性
func (c *Config) Validate() error {
	// 验证端口范围
	if c.GUI.Port < 1024 || c.GUI.Port > 65535 {
		return fmt.Errorf("invalid GUI port: %d (must be 1024-65535)", c.GUI.Port)
	}

	// 验证超时值（0 表示无限等待）
	if c.Defaults.Timeout != 0 {
		if c.Defaults.Timeout < 10 || c.Defaults.Timeout > 86400 {
			return fmt.Errorf("invalid timeout: %d (must be 0 or 10-86400 seconds)", c.Defaults.Timeout)
		}
	}

	// 验证日志级别
	validLevels := map[string]bool{"debug": true, "info": true, "warn": true, "error": true}
	if !validLevels[c.Defaults.LogLevel] {
		return fmt.Errorf("invalid log level: %s (must be debug/info/warn/error)", c.Defaults.LogLevel)
	}

	// 验证健康检查间隔
	if c.GUIService.HealthCheckInterval < 5 || c.GUIService.HealthCheckInterval > 300 {
		return fmt.Errorf("invalid health check interval: %d (must be 5-300 seconds)", c.GUIService.HealthCheckInterval)
	}

	// 验证窗口尺寸
	if c.GUI.WindowWidth < 400 || c.GUI.WindowWidth > 2000 {
		return fmt.Errorf("invalid window width: %d (must be 400-2000)", c.GUI.WindowWidth)
	}
	if c.GUI.WindowHeight < 300 || c.GUI.WindowHeight > 1500 {
		return fmt.Errorf("invalid window height: %d (must be 300-1500)", c.GUI.WindowHeight)
	}

	return nil
}

// DefaultConfig 返回默认配置
func DefaultConfig() *Config {
	return &Config{
		Server: ServerConfig{
			Name:    "mcp-clarification-service",
			Version: "1.0.0",
		},
		GUIService: GUIServiceConfig{
			URL:                 "http://localhost:9080",
			HealthCheckInterval: 30,
			AutoStart:           true,
		},
		Defaults: DefaultsConfig{
			Timeout:  300,
			LogLevel: "info",
		},
		GUI: GUIConfig{
			Port:         9080,
			Theme:        "light",
			WindowWidth:  600,
			WindowHeight: 500,
			AlwaysOnTop:  true,
		},
	}
}
